package com.ww.springboot.boot.thread.threadlocal;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-13 08:59
 */
public class ThreadLocalDemo内存泄露3 {


    private static ThreadLocal<byte[]> threadLocal = new ThreadLocal();

    private static List<Thread> list = new ArrayList<>();

    /**
     * 一个线程可能有多个ThreadLocal 每个ThreadLocal的nextHashCode()只会触发一次
     * 每个threadLocal 在ThreadLocalMap中的位置是固定的
     * <p>
     * <p>
     * ThreadLocalMap key是threadLocal value是值 即使threadLocal弱引用 在
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        Thread.sleep(10000);

        for (int i = 0; i < 1000; i++) {
            Thread.sleep(1000);
            int finalI = i;
            Thread thread = new Thread(() -> {
                threadLocal.set(new byte[finalI * 1024 * 1024]);
            });
            thread.start();
            System.out.println(thread.getName());
            list.add(thread);
            System.out.println(list.size());
        }
    }
}
